//
//  RFConstant.swift
//  RF_localRepo
//
//  Created by zrf on 2021/6/8.
//

import Foundation

/**
 @brief 获取APP名
 @author rf/2021-06-09
 */
public func appName() -> String {
    if let name = Bundle.main.object(forInfoDictionaryKey: "CFBundleDisplayName") as? String {
        return name
    }else{
        return ""
    }
}

/// 获取工程名
/// - Returns: 工程名
public func executableName() -> String{  
    if let name = Bundle.main.object(forInfoDictionaryKey: "CFBundleExecutable") as? String {
        return name
    }else{
        return ""
    }
}
/**
 @brief 获取APP版本号
 @author rf/2021-06-09
 */
public func appVersion() -> String {
    if let name = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String {
        return name
    }else{
        return ""
    }
}
/**
 @brief 获取APP build num
 @author rf/2021-06-09
 */
public func appBuildNum() -> String {
    if let name = Bundle.main.object(forInfoDictionaryKey: kCFBundleVersionKey as String) as? String {
        return name
    }else{
        return ""
    }
}
/**
 @brief 获取APP Bundle ID
 @author rf/2021-06-09
 */
public func appBundleId() -> String {
    if let name = Bundle.main.object(forInfoDictionaryKey: kCFBundleIdentifierKey as String) as? String {
        return name
    }else{
        return ""
    }
}
public func RegularFont(_ size: CGFloat) -> UIFont {
    return UIFont(name:"PingFangSC-Regular", size: size) ?? UIFont.systemFont(ofSize: size)
}

public func SemiblodFont(_ size: CGFloat) -> UIFont {
    return UIFont(name:"PingFangSC-Semibold", size: size) ?? UIFont.systemFont(ofSize: size)
}

public func MediumFont(_ size: CGFloat) -> UIFont {
    return UIFont(name:"PingFangSC-Medium", size: size) ?? UIFont.systemFont(ofSize: size)
}
public func getAppIcon() -> UIImage {
    let appIconName = (((Bundle.main.infoDictionary!["CFBundleIcons"] as! [String: Any])["CFBundlePrimaryIcon"] as! [String: Any])["CFBundleIconFiles"] as! Array<Any>).last as! String
    return UIImage(named: appIconName)!
}
public func AppRootVC() -> UIViewController {
    return (UIApplication.shared.delegate?.window??.rootViewController)!
}
public var lsWindow: UIWindow{
    var window = UIApplication.shared.keyWindow
    if window == nil ||
       window?.windowLevel != .normal {
        for w in UIApplication.shared.windows {
            if w.windowLevel == .normal {
                window = w
                break
            }
        }
    }
    return window!
}

/**
 @brief 通过window获取当前显示的VC
 @author rf/2021-08-25
 */
public var lsCurrentVC: UIViewController?{
    var vc: UIViewController? = nil
    let view = lsWindow.subviews.first
    if view?.next! is UIViewController {
        vc = view?.next as? UIViewController
    }else{
        vc = lsWindow.rootViewController
    }
    return ls_getCurrentShowVC(vc!)
}
fileprivate func ls_getCurrentShowVC(_ vc: UIViewController) -> UIViewController{
    var current: UIViewController? = nil
    //递归查找
    if (vc.presentedViewController != nil) {  //先判断当前视图是否为present
        current = ls_getCurrentShowVC(vc.presentedViewController!)
    }else if let tabbarCtr = vc as? UITabBarController {
        current = ls_getCurrentShowVC(tabbarCtr.selectedViewController!)
    }else if let nav = vc as? UINavigationController{
        current = ls_getCurrentShowVC(nav.visibleViewController!)
    }else{
        current = vc
    }
    return current!
}
/**
 @brief 屏幕宽高
 */
public var lsScreenWidth : CGFloat {
    UIScreen.main.bounds.size.width
}
public var lsScreenHeight : CGFloat {
    UIScreen.main.bounds.size.height
}
//顶部安全区域
public var lsSafeTop : CGFloat {
    if #available(iOS 11.0, *),
       let window = UIApplication.shared.windows.first {
        return window.safeAreaInsets.top
    }
    return 20
}
//底部安全区域
public var lsSafeBottom : CGFloat {
    if #available(iOS 11.0, *),
       let window = UIApplication.shared.windows.first {
        return window.safeAreaInsets.bottom
    }
    return 0
}
//获取本地framework资源信息
//当pod使用 user_framework时，需要从framework中读取到bundle，未使用时可直接获取
public func myBundle(_ name: String = "LSTools", framework: String = "LSTools") -> Bundle?{
    let frameworkUrl = Bundle.main.url(forResource: "Frameworks", withExtension: nil)  //获取framework
//    let url = Bundle.main.url(forResource: name, withExtension: "bundle")  //没有user_framework时直接使用
//    if let url = url {
//        return Bundle(url: url)
//    }
    var bundleUrl = frameworkUrl?.appendingPathComponent(framework)
    bundleUrl?.appendPathExtension("framework")
    if let bundleUrl = bundleUrl {
        let bundle = Bundle(url: bundleUrl)
        let url = bundle?.url(forResource: name, withExtension: "bundle")
        let myBundle = Bundle(url: url!)
        return myBundle
    }else{
        return nil
    }
//    self.imagView.image = [UIImage imageNamed:@"icon_mine_grade"
//      inBundle: bundle
//    compatibleWithTraitCollection:nil];
}
/**
 @brief 自定义打印，只有debug模式下，控制台会打印出信息
 定制化打印，正式环境不答应，打印内容自动存储在本地Log/log.txt，方便根据log追踪问题
 */
public func lsPrint(_ items: Any..., file: String = #file, function: String = #function, isSave: Bool = true){
    
    var log = Date().string() + " " + (file as NSString).lastPathComponent + "." + function + " "
    for item in items{
        if let value = item as? String{
            log += value
        }else if let value = item as? CustomStringConvertible {
            log += value.description
        }
    }
//    log += "\n"
    #if DEBUG
    print(log)
    #endif
    if isSave {
        let logPath = "Log/log.txt"
        if LSPathManager.size(logPath) > 1_024_000 {  //文件大于1M时自动清理
            LSPathManager.del(logPath)
        }
        LSPathManager.insert(logPath, data: log.data)
    }
    
}

/// 通知封装
/// - Parameters:
///   - name: 通知名
///   - object: 额外参数
///   - userInfo: 参数
///   - Authors:rf/2021-11-02
public func lsPostNotify(_ name: String, object: Any? = nil, userInfo: [AnyHashable : Any]? = nil){
    NotificationCenter.default.post(name: NSNotification.Name(name), object: object, userInfo: userInfo)
}
///使用时注意weak self，避免造成循环引入 rf/2022-07-21
public func lsAddNotify(_ name: String, block:@escaping (Notification)->Void){

    NotificationCenter.default.addObserver(forName: NSNotification.Name(name), object: nil, queue: OperationQueue.main) { notify in
        block(notify)
    }
}
